//
//  NDOrderDetailViewModel.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/27.
//

import UIKit
import Combine

class NDOrderDetailViewModel: ObservableObject {
    @Published var orderDetail: NDOrderDetail?
    @Published var isLoading = false
    @Published var errorMessage: String?
    @Published var followOrderModel: FollowOrderModel?
    @Published var shouldNextStep = false
    
    @Published var isFollowedOrder = false
    
    @Published var toNavTitle = ""
    
    deinit {
        // 正确移除所有观察者和订阅
        notificationCancellable?.cancel()
        if let notificationObserver = notificationObserver {
            NotificationCenter.default.removeObserver(notificationObserver)
        }
        cancellables.forEach { $0.cancel() }
        cancellables.removeAll()
    }

    var productId: Int?
    @Published var authType: AuthType = .unknown
    
    private var notificationCancellable: AnyCancellable?
    private var notificationObserver: NSObjectProtocol? // 添加 NSObjectProtocol 观察者
    var nextStepAction: (() -> Void)?
    private var cancellables = Set<AnyCancellable>()
    
    var followOrderAction: ((FollowOrderModel?) -> Void)?
    
    init() {
        setupNotificationObserver()
        setupNextStepHandler()
        setupFollowedOrderHandler()
    }
    
    private func setupNotificationObserver() {
        // 先移除旧的观察者
        if let oldObserver = notificationObserver {
            NotificationCenter.default.removeObserver(oldObserver)
        }
        
        // 使用 NSObjectProtocol 观察者，更容易管理生命周期
        notificationObserver = NotificationCenter.default.addObserver(
            forName: .followUpCurrentProductNotification,
            object: nil,
            queue: .main
        ) { [weak self] _ in
            guard let self = self else { return }
            NDProgressHUD.show()
            self.requestOrderNextStepView()
        }
    }
    
    private func setupNextStepHandler() {
        // 监听 shouldNextStep 的变化并立即执行
        $shouldNextStep
            .filter { $0 }
            .sink { [weak self] _ in
                DispatchQueue.main.async {
                    self?.nextStepAction?()
                    self?.shouldNextStep = false // 重置状态
                }
            }
            .store(in: &cancellables)
    }
    
    private func setupFollowedOrderHandler() {
        // 监听 isFollowedOrder 的变化并立即执行
        $isFollowedOrder
            .filter { $0 }
            .sink { [weak self] _ in
                DispatchQueue.main.async {
                    self?.followOrderAction?(self?.followOrderModel)
                    self?.isFollowedOrder = false // 重置状态
                }
            }
            .store(in: &cancellables)
    }
    
    // 清理方法，可以在 View 消失时手动调用
    func cleanup() {
        notificationCancellable?.cancel()
        notificationCancellable = nil
        
        if let observer = notificationObserver {
            NotificationCenter.default.removeObserver(observer)
            notificationObserver = nil
        }
        
        cancellables.forEach { $0.cancel() }
        cancellables.removeAll()
        
        nextStepAction = nil
        followOrderAction = nil
    }
    
    // 设置下一步动作的回调
    func setNextStepNotification(_ action: @escaping () -> Void) {
        self.nextStepAction = action
    }
    
    func setFollowOrderAction(_ action: @escaping (FollowOrderModel?) -> Void) {
        self.followOrderAction = action
    }

    func loadProductDetailData() {
        isLoading = true
        errorMessage = nil
        guard let productId = productId else {
            self.errorMessage = "no product"
            return
        }
        
        NDRequestManager.requestOrderDetail(productId: productId) { [weak self] detail, msg, error in
            guard let self = self else { return }
            DispatchQueue.main.async {
                
                if let error = error {
                    self.errorMessage = msg
                    self.isLoading = false
                    print("请求失败: \(error)")
                    return
                }
                
                guard let detail = detail else {
                    self.errorMessage = "no data"
                    self.isLoading = false
                    return
                }
                
                self.orderDetail = detail
                self.isLoading = false
            }
        }
    }
    
    func requestOrderNextStepView() {
        
        self.shouldNextStep = false
        self.followOrderModel = nil
        
        guard let productId = productId else {
            return
        }
        
        NDRequestManager.requestOrderDetail(productId: productId) { [weak self] detail, msg, error in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.isLoading = false
                if error != nil {
                    NDProgressHUD.showInfo(msg)
                    return
                }
                
                guard let detail = detail else {
                    return
                }
                
                self.orderDetail = detail
                
                self.shouldNextStep = true
                
                guard let _ = self.nextStep else {
                    self.followCurrentOrder()
                    return
                }
                NDProgressHUD.dismiss()
            }
        }
    }
    
    func followCurrentOrder() {
        self.isFollowedOrder = false
        let startTimeStamp = Int(Date().timeIntervalSince1970)
        guard let productInfo = self.productInfo else {
            return
        }
        NDRequestManager.requestfollowCurrentOrder(productInfo: productInfo) { [weak self] followOrderModel, msg, error in
            guard let self = self else { return }
            DispatchQueue.main.async {
                if error != nil {
                    NDProgressHUD.showInfo(msg)
                    return
                }
                
                guard let followOrderModel = followOrderModel else {
                    return
                }
                
                self.followOrderModel = followOrderModel
                self.isFollowedOrder = true
                NDProgressHUD.dismiss()
                
                NDEventAnallyticsTool.uploadMaiDianEvent(maiDianType: .startLoan,
                                                         productId: self.productId,
                                                         orderNum: self.orderNum,
                                                         startTimeStamp: startTimeStamp,
                                                         endTimeStamp: Int(Date().timeIntervalSince1970))
            }
        }
    }
    
    func requestAddressData() {
        guard let productId = productId else {
            return
        }
        NDRequestManager.requestAddressInfo(productId: productId) { [weak self]  model, msg, error in
            guard let _ = self else { return }
            if error == nil,
               let model = model {
                NDUserDefaults.shared.archiveObject(model, for: NDAddressKey)
            }
        }
    }
    
    var productInfo: NDProductInfo? {
        return orderDetail?.theory
    }
    
    var userInfo: NDUserInfo? {
        return orderDetail?.serprestly
    }
    
    var authItems: [NDAuthItem] {
        return orderDetail?.morningry ?? []
    }
    
    var nextStep: NDNextStep? {
        return orderDetail?.soletacious
    }
    
    var nextStepTitle: String? {
        return nextStep?.pitister
    }
 
    var loanAgreements: [NDLoanAgreement] {
        return orderDetail?.participantance ?? []
    }
    
    var orderNum: String {
        return productInfo?.volvator ?? ""
    }
    
    var currentProductId: Int {
        return Int(productInfo?.selenify ?? "-1") ?? -1
    }
}
